package com.example.demo.Exception;

import cn.hutool.json.JSONUtil;
import com.example.demo.pojo.JsonResult;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AuthenicationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        JsonResult<Object> jsonResult = new JsonResult<>("401", "用户认证失败!请重新登录");
        String fileName = JSONUtil.toJsonStr(jsonResult);
        System.out.println("fileName =AuthenicationEntryPointImpl " + fileName);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter writer = httpServletResponse.getWriter();
        writer.println(fileName);
        writer.flush();
        writer.close();
    }
}
